<template>
  <el-dialog
          :model-value="visible"
          :title="title"
          :before-close="cancelRelateDialog"
          width="70%"
          top="5vh"
  >
    <el-row>
      <el-col :span="24">
        <el-select
                placeholder="选择部门"
                clearable
                v-model="relateQueryList.groupid"
                @change="handleFilter"
                class="mr10 select-w" size="small">
          <el-option
                  v-for="group in groupList"
                  :key="group.groupid"
                  :label="group.name"
                  :value="group.groupid"
          ></el-option>
        </el-select>
        <el-select
                placeholder="选择媒体类型"
                clearable
                v-model="relateQueryList.mediatype"
                @change="handleFilter('mediatype')"
                class="mr10 select-w" size="small"
                >
          <el-option v-for="type in initMediaTypeList"

                     :key="type.mediatype"
                     :value="type.mediatype"
                     :label="type.name"
          ></el-option>
        </el-select>
        <el-cascader clearable
                     placeholder="选择分类"
                     filterable
                     ref="categoryRef"
                     v-model="checkedCategory"
                     :options="categoryList"
                     @change="handleFilter"
                     :props="{value: 'catid', label: 'name', emitPath: true}"
                     class="mr10 select-w" size="small"
        >
        </el-cascader>
        <el-input
                placeholder="媒体名称"
                clearable
                v-model="relateQueryList.keyword"
                class="mr10 input-w" size="small"
                @clear="handleFilter"
                @keyup.enter="handleFilter"
        />
        <el-button type="primary" size="mini" @click="handleFilter">
          <el-icon>
            <search />
          </el-icon>
          搜索
        </el-button>
      </el-col>
      <el-col :span="24" class="mt10">
        <el-table v-loading="isloading" :data="tableData.listData"
                  border max-height="350" highlight-current-row
                  @current-change="handleCurrentChange"
        >
          <el-table-column width="60" align="center">
            <template #default="{row}">
              <el-radio :label="row.mediaid" v-model="relateFormData.mediaid" @click="handleClickRadio(row.mediaid)">{{''}}</el-radio>
            </template>
          </el-table-column>
          <el-table-column label="媒体ID" prop="mediaid" width="100" />
          <el-table-column label="媒体名称" :show-overflow-tooltip="true">
            <template #default="{row}">
              <!--<span v-if="row.highlight && row.highlight.name" v-html="row.highlight.name" class="txttdellipsis">
              </span>-->
              <span class="txttdellipsis" >{{row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column label="媒体类型">
            <template #default="{row}">
              {{row.mediatypename}}
            </template>
          </el-table-column>
          <el-table-column label="媒体分类">
            <template #default="{row}">
              <p>{{row.catname}}</p>
              <p>{{row.subcatnames.join('/')}}</p>
            </template>
          </el-table-column>
          <el-table-column label="所属部门">
            <template #default="{row}">
              {{groupsOptionsData[row.groupid]}}
            </template>
          </el-table-column>
          <el-table-column label="是否有子集" align="center">
            <template #default="{row}">
              <span v-if="row.hasseries == 1">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="mt10">
        <table-pagination
                :queryList="relateQueryList"
                :total="tableData.total"
                @pagination="getDataList"
        />
      </el-col>
    </el-row>
    <template #footer>
      <div align="center">
        <el-button type="default" size="small" @click="cancelRelateDialog">取消</el-button>
        <el-button type="primary" size="small" @click="handleNextStep">下一步</el-button>
      </div>
    </template>
  </el-dialog>
  <do-relate
          ref="doRelateRef"
          :visible="doRelateVisible"
          :dataTmp="relateFormData"
          :seriesQueryList="seriesQueryList"
          @cancelDoRelateDialog="cancelDoRelateDialog"
          @reloadSeriesList="reloadSeriesList"
          @cancelRelateDialog="cancelRelateDialog"
  />
</template>

<script>
  import {toRef, ref, reactive, nextTick} from 'vue'
  import {useStore} from 'vuex'
  import { Search } from "@element-plus/icons"
  import TablePagination from "@/views/public/TablePagination";
  import {getRelMedias, getSeries} from "@/api/media/media";
  import DoRelate from "./components/DoRelate";
  import {getImageRelMedia} from "@/api/media/image";
  import {ElMessage} from 'element-plus'
  import {getVideoRelMedia} from "@/api/media/video";
  import {getMediaTYpe} from "@/api/media/mediatype";
  import {getCategories} from "@/api/media/constant";

  export default {
    name: "index",
    props: {
      visible: {
        type: Boolean,
        default() {
          return false
        }
      },
      title: {
        type: String,
        default: '介质关联媒资'
      },
      groupList: {
        type: Array,
        default() {
          return []
        }
      },
      formData: {
        type: Object
      },
      queryList: {
        type: Object
      },
      relateData: {
        type: Object
      },
      groupsOptions: {
        type: Object
      }
    },
    components: {Search, TablePagination, DoRelate},
    emits: ['cancelRelateDialog'],
    setup(props, context) {
      const store = useStore()
      const relateFormData = toRef(props, 'formData')
      const relateQueryList = toRef(props, 'queryList')
      const isloading = ref(false)
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const initMediaTypeList = ref([])

      const categoryQuery = reactive({
        corpid: store.getters.corpinfo.corpid,
        page: 1,
        pagesize: 10000,
        mediatype: undefined
      })
      const categoryList = ref([])
      const categoryRef = ref(null)
      const checkedCategory = ref([])
      const doRelateVisible = ref(false)
      const seriesQueryList = reactive({
        page: 1,
        pagesize: 25,
        mediaid: undefined,
        keyword: undefined
      })
      const doRelateRef = ref(null)
      const groupsOptionsData = toRef(props, 'groupsOptions')

      const cancelRelateDialog = () => {
        context.emit('cancelRelateDialog')
        resetRelateQueryList()
        getDataList()
      }
      const getDataList = () => {
        isloading.value = true
        relateQueryList.value.corpid = store.getters.corpinfo.corpid
        getRelMedias(relateQueryList.value).then(response => {
          isloading.value = false
          const {total, list} = response.data
          tableData.total = total
          tableData.listData = list
        })
      }
      const handleFilter = (type) => {
        if (type == 'mediatype') {
          categoryRef.value.panel.clearCheckedNodes()
          if (relateQueryList.value.mediatype) {
            categoryQuery.mediatype = relateQueryList.value.mediatype
            getCategories(categoryQuery).then(response => {
              categoryList.value = response.data.list
            })
          } else {
            categoryList.value = []
          }
        }
        if (categoryRef.value.getCheckedNodes(false).length > 0) {
          const checkedCategoryNode = categoryRef.value.getCheckedNodes(false)[0].data
          relateQueryList.value.catid = checkedCategoryNode.catid
        } else {
          relateQueryList.value.catid = undefined
        }
        relateQueryList.value.page = 1
        getDataList()
      }
      const handleNextStep = async() => {
        let flag = true
        if (!relateFormData.value.mediaid) {
          ElMessage({type: 'warning', message: '请选择媒资', duration: 2000})
          flag = false
          return
        }
        tableData.listData.forEach(media => {
          if (media.mediaid == relateFormData.value.mediaid) {
            relateFormData.value.medianame = media.name
            relateFormData.value.tplid = media.tplid
            relateFormData.value.hasseries = media.hasseries
          }
        })
        if (relateFormData.value.imgid) {
          await getImageRelMedia({imgid: relateFormData.value.imgid, mediaid: relateFormData.value.mediaid}).then(response => {
            if (response.errcode == 0) {
              const {media_checked, series_checked, seriesid_list} = response.data
              relateFormData.value.media_checked = media_checked
              relateFormData.value.series_checked = series_checked
              relateFormData.value.seriesid_list = seriesid_list
            } else {
              flag = false
            }
          })
        } else {
          await getVideoRelMedia({videoid: relateFormData.value.videoid, mediaid: relateFormData.value.mediaid}).then(response => {
            if (response.errcode == 0) {
              const {media_checked, series_checked, seriesid_list} = response.data
              relateFormData.value.media_checked = media_checked
              relateFormData.value.series_checked = series_checked
              relateFormData.value.seriesid_list = seriesid_list
            } else {
              flag = false
            }
          })
        }
        doRelateVisible.value = flag
        if (relateFormData.value.hasseries == 1) {
          seriesQueryList.page = 1
          seriesQueryList.keyword = undefined
          getSeriesList()
        }

      }
      const getSeriesList = async() => {
        // 获取子集列表
        seriesQueryList.mediaid = relateFormData.value.mediaid
        await getSeries(seriesQueryList).then(response => {
          relateFormData.value.seriesList = response.data.list
          relateFormData.value.seriesTotal = response.data.total
          nextTick(() => {
            relateFormData.value.seriesList.forEach(series => {
              if (relateFormData.value.seriesid_list.includes(series.seriesid)) {
                doRelateRef.value.seriesTableRef.toggleRowSelection(series, true)
              }
            })
          })
        })
      }
      const cancelDoRelateDialog = () => {
        doRelateVisible.value = false
      }
      const reloadSeriesList = () => {
        getSeriesList()
      }
      const handleClickRadio = (mediaid) => {
        relateFormData.value.mediaid = mediaid
      }
      const resetRelateQueryList = () => {
        categoryList.value = []
        relateQueryList.value.catid = undefined
        relateQueryList.value.mediatype = undefined
        relateQueryList.value.keyword = undefined
        relateQueryList.value.groupid = undefined
      }
      const handleCurrentChange = (row) => {
        if (row) {
          relateFormData.value.mediaid = row.mediaid
        }
      }
      const init = () => {
        getMediaTYpe({
          page: 1,
          pagesize: 10000,
        }).then(response => {
          initMediaTypeList.value = response.data
        })
        getDataList()
      }

      return {
        cancelRelateDialog,
        relateFormData,
        relateQueryList,
        isloading,
        tableData,
        getDataList,
        initMediaTypeList,
        handleFilter,
        categoryList,
        categoryRef,
        checkedCategory,
        handleNextStep,
        doRelateVisible,
        cancelDoRelateDialog,
        seriesQueryList,
        reloadSeriesList,
        handleClickRadio,
        doRelateRef,
        resetRelateQueryList,
        groupsOptionsData,
        handleCurrentChange,
        init
      }
    }
  }
</script>

<style lang="scss">
  .el-table{
    .el-radio__label{
      padding-left:0;
    }
  }
</style>
<style>
  em{
    color: red;
  }
</style>
